package com.gujiangbo.juc;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/6/5 16:08
 * @Version: 1.0
 * @Description:
 */
public class SaleTicketDemo {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread t1 = new Thread(()->{for(int i=0;i<50;i++){ticket.sale();}},"a");
        Thread t2 = new Thread(()->{for(int i=0;i<50;i++){ticket.sale();}},"b");
        Thread t3 = new Thread(()->{for(int i=0;i<50;i++){ticket.sale();}},"c");
        t1.start();
        t2.start();
        t3.start();
    }
}


class Ticket {

    private int number = 50;

    ReentrantLock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第:" + (number--) + "张票,还剩下:" + number + "张");
            }
        } finally {
            lock.unlock();
        }

    }
}
